#import "RNPrintContainerCell.h"
#import "RNConstants.h"

static NSUInteger const countWidth = 50;
static NSUInteger const countLeftPadding = 10;
static NSUInteger const titleLeftPadding = 5;

@implementation RNPrintContainerCell

@synthesize titleAttributes = titleAttributes_;
@synthesize countAttributes = countAttributes_;

-(id)initTextCell:(NSString *)title {
    if (!(self = [super initTextCell:title]))
        return nil;
    
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    [attributes setValue:[NSFont fontWithName:@"Palatino" size:12.0f] forKey:NSFontAttributeName];
    [self setTitleAttributes:attributes];
    
    attributes = [NSMutableDictionary dictionary];
    [attributes setValue:[NSFont fontWithName:@"Palatino" size:10.0f] forKey:NSFontAttributeName];
    [attributes setValue:[NSColor colorWithCalibratedWhite:0.5 alpha:1.0] forKey:NSForegroundColorAttributeName];
    [self setCountAttributes:attributes];
    
    return self;
}

-(void)setObjectValue:(id)obj {
    if (![obj isKindOfClass:[NSDictionary class]])
        return;
    [super setObjectValue:obj];
}

-(void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    // Draw count
    NSAttributedString *count = [self attributedCount];
    if (count)
        [count drawInRect:[self countRectForBounds:cellFrame]];
    
    // Draw title
    NSString *titleString = [[self objectValue] valueForKey:RNTitleKey];
    NSAttributedString *title = [[NSAttributedString alloc] initWithString:titleString attributes:[self titleAttributes]];
    [title drawInRect:[self titleRectForBounds:cellFrame]];
}

-(NSRect)titleRectForBounds:(NSRect)cellFrame {
    NSRect titleRect = cellFrame;
    CGFloat xAdjustment = titleLeftPadding + countLeftPadding + countWidth;
    titleRect.origin.x += xAdjustment;
    titleRect.size.width -= xAdjustment;
    return titleRect;
}

-(NSRect)countRectForBounds:(NSRect)bounds {
    NSRect countRect = bounds;
    CGFloat xAdjustment = countLeftPadding;
    countRect.origin.x += xAdjustment;
    countRect.size.width = countWidth;
    countRect.origin.y += 2;
    return countRect;
}

-(NSAttributedString *)attributedCount {
    NSInteger itemCount = [[[self objectValue] valueForKey:@"itemsCount"] integerValue];
    NSString *itemCountString = [NSString stringWithFormat:@"%i %@", itemCount, (itemCount == 1 ? @"item" : @"items")];
    return [[NSAttributedString alloc] initWithString:itemCountString attributes:[self countAttributes]];
}

@end
